package com.thiswhyme.demo.msgpush.core.impl.nio.event;

import com.thiswhyme.demo.msgpush.core.event.AbstractBroadcastEventHandler;
import com.thiswhyme.demo.msgpush.core.event.bean.WebSocketEvent;
import com.thiswhyme.demo.msgpush.core.impl.nio.ChannelManager;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @description: WebSocket消息广播事件处理器-nio
 * @author: thiswhyme
 * @date: 2021/9/28
 */
@Slf4j
public class BroadcastEventNioHandler extends AbstractBroadcastEventHandler {

    @Override
    public void doHandle(WebSocketEvent event) {
        Map<String, Channel> channels = ChannelManager.getUserChannelMap();
        if (CollectionUtils.isEmpty(channels)) {
            log.warn("该实例上没有可用的Channel，跳过处理");
            return;
        }

        channels.forEach((identifier, channel) -> {
            if (null != channel && channel.isOpen()) {
                channel.writeAndFlush(new TextWebSocketFrame(event.getMsgContent()));
                log.debug("【{}】完成广播", identifier);
            } else {
                log.error("【{}】广播失败，Channel已关闭", identifier);
            }
        });
    }
}